﻿using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Extensions.FileProviders;
using ZYing.LiquidThemeEngine.FileProviders;

namespace ZYing.LiquidThemeEngine
{
    internal static class Helper
    {
        public static string CombinePath(params string[] paths)
        {
            return Path.Combine(paths);
        }
        /// <summary>
        ///     Compares the string against a given pattern.
        /// </summary>
        /// <param name="str">The string.</param>
        /// <param name="pattern">
        ///     The pattern to match, where "*" means any sequence of characters, and "?" means any single
        ///     character.
        /// </param>
        /// <returns><c>true</c> if the string matches the given pattern; otherwise <c>false</c>.</returns>
        public static bool Like(this string str, string pattern)
        {
            return new Regex(
                "^" + Regex.Escape(pattern).Replace(@"\*", ".*").Replace(@"\?", ".") + "$",
                RegexOptions.IgnoreCase | RegexOptions.Singleline
            ).IsMatch(str);
        }

        public static async Task<string> ReadAsStringAsync(IFileInfo fileInfo)
        {
            using (var stream = fileInfo.CreateReadStream())
            {
                using (var streamReader = new StreamReader(stream, Encoding.UTF8, true))
                {
                    return await streamReader.ReadToEndAsync();
                }
            }
        }

        public static string NormalTemplateName(string name)
        {
            if (string.IsNullOrWhiteSpace(name)) return string.Empty;

            if (name.EndsWith(Constants.TemplateExtension, StringComparison.OrdinalIgnoreCase))
            {
                var len = name.Length - Constants.TemplateExtension.Length;
                return name.Substring(0, len);
            }

            return name;
        }

        public static string NormalTemplateFile(string name)
        {
            if (string.IsNullOrWhiteSpace(name)) return string.Empty;

            if (name.EndsWith(Constants.TemplateExtension, StringComparison.OrdinalIgnoreCase)) return name;

            return name + Constants.TemplateExtension;
        }

        public static async Task<String> ReadAsStringAsync(ILiquidThemeFileInfo file)
        {
            using (var stream = file.CreateReadStream())
            {
                using (var streamReader = new StreamReader(stream, Encoding.UTF8, true))
                {
                    return await streamReader.ReadToEndAsync();
                }
            }
        }
    }
}